package com.lzjt.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtils {

    // 设置 token 过期时间（单位：毫秒）
    private static final long EXPIRE = 1000 * 60 * 60 * 24; // 例如：24小时

    // 设置签名密钥（建议从配置文件读取）
    private static final String APP_SECRET = "your-secret-key-here";

    public static String getJwtToken(Long id, String uname, String role) {
        return Jwts.builder()
            .setHeaderParam("typ", "JWT")
            .setHeaderParam("alg", "HS256")
            .setSubject("medical-user")
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
            .claim("id", id)
            .claim("uname", uname)
            .claim("role", role)
            .signWith(SignatureAlgorithm.HS256, APP_SECRET)
            .compact();
    }

    public static boolean checkToken(String jwtToken) {
        if (!StringUtils.hasLength(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean checkToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        return checkToken(jwtToken);
    }

    public static Claims getClaims(String jwtToken) {
        if (!StringUtils.hasLength(jwtToken)) return null;
        return Jwts.parser()
                   .setSigningKey(APP_SECRET)
                   .parseClaimsJws(jwtToken)
                   .getBody();
    }

    public static String getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if (!StringUtils.hasLength(jwtToken)) return "";
        return (String) Jwts.parser()
                            .setSigningKey(APP_SECRET)
                            .parseClaimsJws(jwtToken)
                            .getBody()
                            .get("id");
    }
}
